public class Solution1583 {
    public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
        int[][] relation=new int[n][n];
        int[] map=new int[n];
        for (int i=0;i<n;i++){
            for (int j=0;j<n-1;j++){
                relation[i][preferences[i][j]]=j;
            }
        }
        for (int[] pair : pairs) {
            map[pair[0]]=pair[1];
            map[pair[1]]=pair[0];
        }
        int ans=0;
        for (int i=0;i<n;i++){
            int y=map[i];
            for (int j=0;j<n;j++){
                if (i!=j && y!=j){
                    int v=map[j];
                    if (relation[i][j]<relation[i][y] && relation[j][i]<relation[j][v]){
                        ans++;
                        break;
                    }
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1583().unhappyFriends(4,new int[][]{{1,2,3},{3,2,0},{3,1,0},{1,2,0}},new int[][]{{0,1},{2,3}}));
    }
}
